import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import { createPinia } from 'pinia'
import { 
  Button, 
  Form, 
  Field, 
  CellGroup, 
  Toast, 
  Dialog,
  Calendar as VanCalendar,
  Popup,
  ActionSheet,
  NavBar,
  Icon,
  Cell,
  Tag,
  Empty,
  Loading,
  Checkbox,
  DatePicker,
  Picker,
  SwipeCell,
  PullRefresh,
  Notify,
  ConfigProvider,
  Switch,
  Tabbar,
  TabbarItem
} from 'vant'
import 'vant/lib/index.css'
import '@vant/touch-emulator'

import App from './App.vue'
import Login from './views/Login.vue'
import Home from './views/Home.vue'
import CalendarView from './views/Calendar.vue'
import Records from './views/Records.vue'
import Statistics from './views/Statistics.vue'
import { setupInterceptors, useAppStore } from './stores/index.js'

// 路由配置
const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login, meta: { title: '登录' } },
  { 
    path: '/home', 
    component: Home, 
    meta: { title: '首页', requiresAuth: true },
    children: [
      { path: '', redirect: '/home/calendar' },
      { path: 'calendar', component: CalendarView, meta: { title: '日历' } },
      { path: 'records', component: Records, meta: { title: '休息记录' } },
      { path: 'statistics', component: Statistics, meta: { title: '统计' } }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫：检查登录状态
router.beforeEach((to, from, next) => {
  const satoken = localStorage.getItem('satoken')
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title + ' - 工作时间记录'
  }
  
  // 需要登录但未登录，跳转到登录页
  if (to.meta.requiresAuth && !satoken) {
    next('/login')
  } else {
    next()
  }
})

const app = createApp(App)
const pinia = createPinia()

// 注册Vant组件
app.use(Button)
app.use(Form)
app.use(Field)
app.use(CellGroup)
app.use(Toast)
app.use(Dialog)
app.use(VanCalendar)
app.use(Popup)
app.use(ActionSheet)
app.use(NavBar)
app.use(Icon)
app.use(Cell)
app.use(Tag)
app.use(Empty)
app.use(Loading)
app.use(Checkbox)
app.use(DatePicker)
app.use(Picker)
app.use(SwipeCell)
app.use(PullRefresh)
app.use(Notify)
app.use(ConfigProvider)
app.use(Switch)
app.use(Tabbar)
app.use(TabbarItem)

app.use(pinia)
app.use(router)

// 初始化 store 并设置拦截器
const store = useAppStore()
setupInterceptors(store, router)

app.mount('#app')

